package com.jmga.ecogasfinder.activities.maps.overlays;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.util.Log;
import android.view.MotionEvent;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.jmga.ecogasfinder.R;
import com.jmga.ecogasfinder.activities.gasstation.GasStationTabsViewActivity;
import com.jmga.ecogasfinder.activities.maps.ECOGasStationFinderMapActivity;
import com.jmga.ecogasfinder.providers.GasFinderProvider;
import com.jmga.ecogasfinder.utilities.Tools;

public class GasStationsOverlay extends ItemizedOverlay<OverlayItem> {

	public static final String OPEN_CONTEXT_MENU_ACTION = "OPEN_CONTEXT_MENU_ACTION";
	public static final String SET_FAVOURITE_ACTION = "SET_FAVOURITE_ACTION";
	public static final String GET_ROUTE_ACTION = "GET_ROUTE_ACTION";
	public static final String X_COORD_POINTED = "X_COORD_POINTED";
	public static final String Y_COORD_POINTED = "Y_COORD_POINTED";
	public static final int ACTION_VIEW = 0;
	public static final int ACTION_FAVOURITE = 1;
	public static final int ACTION_GET_ROUTE = 2;
	
	private static Context mContext;
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private long endTime, startTime;
	private boolean triggeredDown = false, triggeredUp = false, eventThrown = false;;
	
	
	public GasStationsOverlay(Drawable defaultMarker, Context context) {
		  super(boundCenterBottom(defaultMarker));
		  GasStationsOverlay.mContext = context;
		  populate();
		}

	public void addOverlay(OverlayItem overlay, Drawable drawable) {
		if(drawable != null) {
			overlay.setMarker(boundCenterBottom(drawable));
		}
		this.mOverlays.add(overlay);
		populate();
	}
	
	@Override
	protected OverlayItem createItem(int i) {
	  return this.mOverlays.get(i);
	}
	
	@Override
	public int size() {
	  return this.mOverlays.size();
	}
	
	@Override
	protected boolean onTap(int index) {
		Log.d(getClass().getName(), "onTap (index): " + index);
	  if(GasStationsOverlay.mContext != null && this.mOverlays.size() > index) {
		  final OverlayItem overlayItem = this.mOverlays.get(index);
		  Log.d(getClass().getName(), "item on (" + overlayItem.getPoint().getLongitudeE6() + "," +overlayItem.getPoint().getLatitudeE6() +  ")");
		  String favouriteChoice = GasStationsOverlay.mContext.getString(R.string.action_add_favourite);
		  String[] gasStationParams =  overlayItem.getSnippet().trim().split("@@");
		  final boolean isFavouriteSelected =  Boolean.parseBoolean(gasStationParams[0]);
		  final String xKeySelected = gasStationParams[1];
		  final String xCoordSelected = gasStationParams[2];
		  final String yCoordSelected = gasStationParams[3];
		  if(isFavouriteSelected) {
			  favouriteChoice = GasStationsOverlay.mContext.getString(R.string.action_remove_favourite);
		  }
		  
		  final CharSequence[] items =  {GasStationsOverlay.mContext.getString(R.string.action_view),
				  favouriteChoice, GasStationsOverlay.mContext.getString(R.string.action_get_route)};

		  AlertDialog.Builder builder = new AlertDialog.Builder(GasStationsOverlay.mContext);
          
          Location location = new Location("dummyGPS");
          location.setLongitude(Double.parseDouble(xCoordSelected));
          location.setLatitude(Double.parseDouble(yCoordSelected));

          double dist = getDistanceDriving(((ECOGasStationFinderMapActivity) GasStationsOverlay.mContext).getMyLocationOverlay(), location);
		  builder.setTitle(overlayItem.getTitle() + GasStationsOverlay.mContext.getString(R.string.euroCurrencyLabel) + " (" + dist + " km)");
		  
		  builder.setItems(items, new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int item) {
		    	  Intent intent = null;
		    	  ((ECOGasStationFinderMapActivity) GasStationsOverlay.mContext).setSelectedGasStationByCoords(xCoordSelected, yCoordSelected, xKeySelected);
		    	  switch (item) {
		    	  	case ACTION_VIEW:
		    	  		Intent i = new Intent(GasStationsOverlay.mContext, GasStationTabsViewActivity.class);
		    	  		i.putExtra(GasFinderProvider.KEY_STATION, ((ECOGasStationFinderMapActivity) GasStationsOverlay.mContext).getSelectedGasStation());
		    	  		GasStationsOverlay.mContext.startActivity(i);
		    			break;
					case ACTION_FAVOURITE:
		    			intent = new Intent(GasStationsOverlay.SET_FAVOURITE_ACTION);
		    			Log.d(getClass().getName(), "ACTION_FAVOURITE to " + !isFavouriteSelected + "(" + overlayItem.getPoint().getLongitudeE6() + "," +overlayItem.getPoint().getLatitudeE6() +  ")");
		    			intent.putExtra(GasStationsOverlay.X_COORD_POINTED, overlayItem.getPoint().getLongitudeE6());
		    			intent.putExtra(GasStationsOverlay.Y_COORD_POINTED, overlayItem.getPoint().getLatitudeE6());
		    			intent.putExtra(GasFinderProvider.KEY_FAVOURITE, !isFavouriteSelected);
		    			intent.putExtra(GasFinderProvider.KEY_XKEY, xKeySelected);
		    			GasStationsOverlay.sendBroadcast(intent);
					break;
					case ACTION_GET_ROUTE:
		    			intent = new Intent(GasStationsOverlay.GET_ROUTE_ACTION);
		    			Log.d(getClass().getName(), "ACTION_GET_ROUTE (" + overlayItem.getPoint().getLongitudeE6() + "," +overlayItem.getPoint().getLatitudeE6() +  ")");
		    			intent.putExtra(GasStationsOverlay.X_COORD_POINTED, overlayItem.getPoint().getLongitudeE6());
		    			intent.putExtra(GasStationsOverlay.Y_COORD_POINTED, overlayItem.getPoint().getLatitudeE6());
		    			GasStationsOverlay.sendBroadcast(intent);
						break;
				}
		      }
		  });
		  AlertDialog alert = builder.create();
		  alert.show();
	  }
	  return true;
	}

	private double getDistanceDriving(Location locationA,
			Location locationB) {		
		String gmapsFeed = GasStationsOverlay.mContext.getString(R.string.gmaps_feed);

		return Tools.getDistanceDriving(gmapsFeed, locationA, locationB);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		Log.d(getClass().getName(), "onTouchEvent: " + event.getAction() + "-triggeredDown=" + triggeredDown + "-triggeredUp=" + triggeredUp + "-eventThrown=" +eventThrown);
		if(eventThrown) {
	   		triggeredDown = false;
    		triggeredUp = false;
		}
		
		if(!triggeredDown && event.getAction() == MotionEvent.ACTION_DOWN) {
    		startTime = event.getEventTime();
    		triggeredDown = true;
    		eventThrown = false;
    	} else if(triggeredDown && !triggeredUp && event.getAction() == MotionEvent.ACTION_UP) {
	    	endTime = event.getEventTime();
	    	triggeredUp = true;
	    }
	
		boolean intentSent = false;
    	if(triggeredDown && triggeredUp) {
    		if((endTime - startTime) > 1000) {
    			Log.d(getClass().getName(), "Enviando Intent");
    			Intent intent = new Intent(GasStationsOverlay.OPEN_CONTEXT_MENU_ACTION);
    			intent.putExtra(GasStationsOverlay.X_COORD_POINTED, event.getX());
    			intent.putExtra(GasStationsOverlay.Y_COORD_POINTED, event.getY());
    			sendBroadcast(intent);
    			intentSent = true;
    		}
    		eventThrown = true;
        }
    	
    	if(intentSent) {
    		return true;
    	}
    	
		return super.onTouchEvent(event, mapView);
	}
	
	public void clearItems() {
		mOverlays.clear();
		populate();
	}
	
	public static void sendBroadcast(Intent intent) {
		GasStationsOverlay.mContext.sendBroadcast(intent);
	}
	
}
